# Create your views here.
from bank.app.models import Account, Payment, Card
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.db.models import Q
import datetime
from django.template import RequestContext
from django.views.decorators.http import require_POST
from bank.app.forms import TransferForm, PaymentForm
from bank.app.mobile import render_agent
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import logout
from django.contrib.auth import authenticate, login
from bank.app.cli import direct_command, error_messages


def app_login(request, login_type=None):

    if login_type == 'cli':
        request.session['cli'] = True
    else:
        request.session['cli'] = False
    
    print "here"
    print request.POST
    
    if request.method == 'POST':
        print "here2"
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            print "here3"
            user = authenticate(
                    username=form.cleaned_data['username'], 
                    password=form.cleaned_data['password']
                    )

            if user is not None:
                if user.is_active:
                    login(request, user)
                    print "here4"
                    print login_type
                    if login_type == 'cli':
                        request.session['cli'] = True
                    else:
                        request.session['cli'] = False
                    # Redirect to a success page.
                    return redirect("/bank/app/accounts")
                else:
                    # Return a 'disabled account' error message
                    print "disabled account"
            else:
                # Return an 'invalid login' error message.
                print "invalid login" 
    else:
        form = AuthenticationForm()
    
    return render_agent(request,"registration/login_app.html", {'form':form}, context_instance=RequestContext(request))
    
def app_logout(request):
    logout(request)
    return render_agent(request,"registration/logged_out_app.html")

@login_required
def cli_home(request):
    request.session['cli'] = True
    
    if 'error' in request.GET and request.GET['error']:
        if request.GET['error'] in error_messages:
            errorMsg = error_messages[request.GET['error']]
            return render_agent(request,"cli/cli_content.html", {'error':errorMsg})
    
    return render_agent(request,"cli/cli_content.html")

@login_required
@require_POST
def action_dispatch(request):
    if request.POST["c"]:
        #clear extra whitespace
        context = {'command_arr' : request.POST["c"].split()}

        return direct_command(request, context)
        

    response = redirect('cli_home')
    response['Location'] += '?error=missingCommand'
    return response

@login_required
def list_accounts(request):
    accounts = Account.objects.filter(user=request.user)
    total = 0
    
    for account in accounts:
        total += account.balance
    
    return render_agent(request, "accounts.html", {'accounts' : accounts, 'total':total})

@login_required
def account_details(request, account_id):
    account = Account.objects.get(user=request.user, id=account_id)
    payments = Payment.objects.filter(Q(to_account=account) | Q(from_account=account))
    return render_agent(request,'account_details.html', {'account':account,
                                                           'payments':payments})

@login_required
def list_payments(request, account_id=None, detail=None):
    print "Account id", account_id, " Detail", detail
    if account_id is None:
        accounts = Account.objects.filter(user=request.user)
        if detail is None:
            payments = Payment.objects.filter(Q(to_account__in=accounts) | Q(from_account__in=accounts))
            return render_agent(request,'payments.html', {'user':request.user,'payments' : payments, 'payments_caption':"All activity"})
        elif detail == unicode('from'):
            from_payments = Payment.objects.filter(from_account__in=accounts)
            return render_agent(request,'payments.html', {'from':True,'user':request.user,'payments' : from_payments, 'payments_caption':"Payments from all your accounts"})   
        elif detail == unicode('to'):
            to_payments = Payment.objects.filter(to_account__in=accounts)
            return render_agent(request,'payments.html', {'to':True,'user':request.user,'payments':to_payments, 'payments_caption':"Payments to all your accounts"})
    else:
        account = Account.objects.get( user=request.user, id=account_id)
        print account.name
        if detail is None:
            payments = Payment.objects.filter(Q(from_account=account)|Q(to_account=account))
            return render_agent(request,'payments.html', {'account':account,'payments':payments, 'payments_caption':"All payments related to "+account.name})
        elif detail == unicode('from'):
            from_payments = Payment.objects.filter(from_account=account)
            return render_agent(request,'payments.html', {'from':True,'account':account,'payments' : from_payments, 'payments_caption':"Payments from "+account.name})   
        elif detail == unicode('to'):
            to_payments = Payment.objects.filter(to_account=account)
            return render_agent(request,'payments.html', {'to':True, 'account':account, 'payments':to_payments, 'payments_caption':"Payments to "+account.name})
        
@login_required
def list_payments_by_time(request, year, month=None, day=None):
    if day is not None:
        date = datetime.date(year,month,day)
        payments = Payment.objects.filter(Q(to_account__user=request.user)|Q(from_account__user=request.user), expiration_date=date)
        return render_agent(request,'payments.html', {'user':request.user, 'payments':payments, 'payments_caption':"All account activity " + date.__str__()})
    elif month is not None:
        payments = Payment.objects.filter(Q(to_account__user=request.user)|Q(from_account__user=request.user), expiration_date__year=year, expiration_date__month=month)
        return render_agent(request,'payments.html', {'user':request.user,'payments':payments, 'payments_caption':"All account activity in year " + year.__str__() + " month " + month.__str__()})
    else:
        payments = Payment.objects.filter(Q(to_account__user=request.user)|Q(from_account__user=request.user), expiration_date__year=year)
        return render_agent(request,'payments.html', {'user':request.user,'payments':payments, 'payments_caption':"All account activity in year " + year.__str__()})

@login_required
def payment_details(request, payment_id, account_id=None):
    if account_id is None:
        payment = Payment.objects.get(Q(to_account__user=request.user) | Q(from_account__user=request.user), id=payment_id)
        return render_agent(request,'payment_details.html', {'payment' : payment})
    else:
        account = Account.objects.get(user=request.user, id=account_id)
        payment = Payment.objects.get(Q(to_account=account) | Q(from_account=account), id=payment_id)
        return render_agent(request,'payment_details.html', {'account':account,'payment' : payment})

@login_required
def list_cards(request, account_id=None):
    if account_id is None:
        accounts = Account.objects.filter(user = request.user)
        cards = Card.objects.filter(account__in=accounts)
        return render_agent(request,"cards.html", {'cards' : cards})
    else:    
        account = Account.objects.get(user = request.user, id=account_id)
        cards = Card.objects.filter(account=account)
        return render_agent(request,"cards.html", {'account':account,'cards' : cards})

@login_required
def card_details(request, card_id, account_id=None):
    if account_id is None:
        card = Card.objects.get(account__user = request.user, id=card_id)
        return render_agent(request,"card_details.html", {'card': card})
    else:
        account = Account.objects.get(user = request.user, id = account_id)
        card = Card.objects.get(account=account, id=card_id)
        return render_agent(request,"card_details.html", {'account':account,'card':card})

@login_required
def payments_by_card(request, card_id):
    pass
@login_required
def new_payment(request, account_id=None):
    context = {}
    if request.method == 'POST':
        form = PaymentForm(request.POST)
        if form.is_valid():
            #TODO processing
            pass
    else:
        form = PaymentForm()
        
    field = form.fields['from_account']
    field.queryset = Account.objects.filter(user=request.user)
    if account_id is not None:
        field.initial = account_id 
        
    context['form'] = form
    return render_agent(request,"new_payment.html", context, RequestContext(request))

@login_required
def transfer(request):
    accounts = Account.objects.filter(user=request.user)
    if request.method == 'POST': # If the form has been submitted...
        form = TransferForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            return render_agent(request,"transfer.html")
    else:
        form = TransferForm()
    
    form.fields["from_account"].queryset = accounts
    form.fields["to_account"].queryset = accounts
    return render_agent(request,"transfer.html", {'form':form}, context_instance=RequestContext(request))
